<template>
  <div class="picture">
    <!-- 筛选条件 -->
    <n-form
      label-placement="left"
      label-align="right"
      :show-label="true"
      ref="searchFormRef"
      inline
      :label-width="85"
      :model="searchForm"
      class="picture__form"
    >
      <n-grid cols="24" x-gap="10" item-responsive responsive="screen">
        <n-grid-item span="24 m:12 l:8">
          <n-form-item label="名称：" path="title">
            <n-input
              v-model:value="searchForm.title"
              placeholder="输入名称"
            />
          </n-form-item>
        </n-grid-item>
        <n-grid-item span="24 m:12 l:8">
          <n-form-item label="标签：" path="email">
            <n-input
              v-model:value="searchForm.picTags"
              placeholder="输入标签"
            />
          </n-form-item>
        </n-grid-item>
        <n-grid-item span="24 m:12 l:8">
          <n-form-item label="拍摄时间：" path="captureTime">
            <n-date-picker
              v-model:formatted-value="searchForm.captureTime"
              placeholder="请选择拍摄时间"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </n-form-item>
        </n-grid-item>
        <n-grid-item span="24 m:12 l:8">
          <n-form-item label="描述：" path="description">
            <n-input
              v-model:value="searchForm.description"
              placeholder="请输入描述关键词"
            />
          </n-form-item>
        </n-grid-item>
        <n-grid-item span="24 m:12 l:8">
          <n-form-item label="是否精选：" path="isExcellent">
            <n-checkbox
              v-model:checked="searchForm.isExcellent"
              checked-value="1"
              unchecked-value="0"
            >
              精选
            </n-checkbox>
          </n-form-item>
        </n-grid-item>
        <n-grid-item span="24 m:12 l:8">
          <n-form-item label="是否主图：" path="isMainPic">
            <n-checkbox
              v-model:checked="searchForm.isMainPic"
              checked-value="1"
              unchecked-value="0"
            >
              主图
            </n-checkbox>
          </n-form-item>
        </n-grid-item>
        <n-grid-item span="24 m:24 l:24">
          <n-form-item>
            <n-space>
              <n-button type="primary" attr-type="button" @click="refreshData">搜索</n-button>
            </n-space>
          </n-form-item>
        </n-grid-item>
      </n-grid>
    </n-form>

    <!-- 图片列表 -->
    <div class="picture__list">
      <div class="picture__list__content">
        <n-image-group>
          <div
            v-for="(pic, ind) in pictureList"
            :key="ind"
            :style="{ marginLeft: !ind ? '' : '8px' }"
            class="picture__list__row"
          >
            <!-- 图片列表 -->
            <div
              v-for="(p, i) in pic"
              :key="i"
              class="picture__list__cell"
              :style="{ paddingTop: 1 / (p.wh_radio - 0) * 100 + '%' }"
            >
              <div>
                <!-- 图片 -->
                <n-image
                  width="100%"
                  :src="p.url || '#'"
                  :previewed-img-props="{ style: { border: '8px solid white' } }"
                />
                <!-- 图片操作 -->
                <div class="overlay">
                  <div class="overlay-controls">
                    <div class="left-icon">
                      <n-popover
                        v-for="item in props.leftTopOperate"
                        :key="item.id"
                        trigger="hover"
                        placement="bottom-start"
                        :show-arrow="false"
                        style="background-color: #121212; color: #efefef"
                      >
                        <template #trigger>
                          <div :class="[item.isActive?.(p) ? 'is-active' : '']" @click="item.handler(p)">
                            <n-icon size="16" :component="item.icon" />
                          </div>
                        </template>
                        <span>{{ item.tip }}</span>
                      </n-popover>
                    </div>
                    <div class="right-icon">
                      <div @click="() => handlerSubmitReview(p)">提交审核</div>
                      <div @click="() => handlerPicItem(p)">编辑</div>
                    </div>
                  </div>
                  <div class="overlay-bottom">{{ p.title }}</div>
                </div>
              </div>
            </div>
          </div>
        </n-image-group>
      </div>
      <!-- 分页 -->
      <div class="picture__list__pagination">
        <div class="left">
          {{ pageSize * (pageNumber - 1) }}-{{ pageSize * pageNumber }} of
          {{ total }} images
        </div>
        <div class="middle">
          <n-button @click="nextPage" type="primary">下一页</n-button>
        </div>
        <div class="right">
          <n-pagination v-model:page="pageNumber" :page-count="pageCount" simple @update:page="handlerUpdatePage" />
        </div>
      </div>
    </div>

    <!-- 修改图片信息 -->
    <div class="picture__edit">
      <n-card
        :segmented="{ content: true, footer: 'soft' }"
        header-style="font-size:14px;"
        title="编辑图片"
      >
        <template #header-extra> XXX </template>
        <n-spin :show="loading">
          <n-form
            ref="formRef"
            :model="editForm"
            :rules="rules"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
          >
            <n-form-item label="是否显示" path="isShow">
              <n-checkbox v-model:checked="editForm.isShow" checked-value="1" unchecked-value="0" />
            </n-form-item>
            <n-form-item label="名称" path="title">
              <n-input v-model:value="editForm.title" placeholder="请输入名称" />
            </n-form-item>
            <n-form-item label="标签">
              <n-input v-model:value="editForm.picTags" placeholder="请输入标签" />
            </n-form-item>
            <n-form-item label="拍摄时间">
              <n-date-picker
                clearable
                value-format="yyyy-MM-dd"
                v-model:formatted-value="editForm.captureTime"
                type="date"
                placeholder="请选择拍摄时间"
              />
            </n-form-item>
            <n-form-item label="描述">
              <n-input
                v-model:value="editForm.description"
                placeholder="请输入描述"
              />
            </n-form-item>
            <n-form-item label="图片宽高">
              <n-input
                v-model:value="editForm.pixelWidth"
                placeholder="请输入像素宽"
              />&nbsp;px
              <n-input
                v-model:value="editForm.pixelHeight"
                placeholder="请输入像素高"
              />
            </n-form-item>
            <n-form-item label="光圈">
              <n-input
                v-model:value="editForm.aperture"
                placeholder="请输入使用光圈"
              />
            </n-form-item>
            <n-form-item label="焦段">
              <n-input
                v-model:value="editForm.focalLength"
                placeholder="请输入使用焦段"
              />
            </n-form-item>
            <n-form-item label="快门速度">
              <n-input
                v-model:value="editForm.shutter"
                placeholder="请输入使用快门速度"
              />
            </n-form-item>
            <n-form-item label="ISO">
              <n-input
                v-model:value="editForm.iso"
                placeholder="请输入使用ISO"
              />
            </n-form-item>
          </n-form>
        </n-spin>
        <template #action>
          <n-space justify="end">
            <n-button attr-type="button" type="success" @click="editPicture"
              >提交数据</n-button
            >
          </n-space>
        </template>
      </n-card>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, inject, ref, computed, onMounted, Ref, watch } from "vue";
import {
  NButton,
  NPagination,
  NCard,
  NForm,
  NFormItem,
  NSpace,
  NGrid,
  NGridItem,
  NInput,
  NCheckbox,
  NDatePicker,
  NSpin,
  NImage,
  NImageGroup
} from "naive-ui";
import {
  updatePicture,
  searchPicture,
} from "../api/pictrue";
import { useDebounceFn } from "@vueuse/core";
import { exchangeKey } from "../utils/index";

const props = withDefaults(
  defineProps<{
    leftTopOperate: Array<{
      id: number;
      handler: Function;
      icon: any;
      tip: string;
      isActive: Function; // 是否激活
    }>;
    dataParams: Object;
  }>(),
  {
    leftTopOperate: () => ([]),
    dataParams: () => ({}),
    isActive: () => {},
  }
);

// 查询筛选部分
const searchFormRef = ref(null);
const searchForm = reactive({
  title: "",
  picTags: "",
  captureTime: null,
  description: "",
  isExcellent: "",
  isMainPic: "",
});

// 查询列表数据
const refreshData = useDebounceFn(() => {
  _getPictrueData();
}, 300);

const loading = ref(false); // 加载中

const pictureList: Ref<any[]> = ref([]); // 指定日期的图片
const pageNumber = ref(1); // 第几页
const pageSize = ref(10); // 一页多少个
const total = ref(0); // 总量
const pageCount = ref(1); // 总页数

// 获取照片
const _getPictrueData = () => {
  loading.value = true;
  console.log("1", props.dataParams);
  const params = {
    ...props.dataParams,
    pageNumber: pageNumber.value,
    pageSize: pageSize.value,
    ...searchForm,
    orders: {
      column: "capture_time",
      order: "desc",
    }
  };
  if (params.isExcellent === "0") params.isExcellent = "";
  if (params.isMainPic === "0") params.isMainPic = "";
  pictureList.value = [];
  searchPicture(params)
    .then((res: any) => {
      const data = res?.data?.list || [];
      total.value = res?.data?.total || 0;
      pageCount.value = Math.ceil(total.value / pageSize.value);
      // 处理图片为散列格式
      const num = Math.floor(data.length / 3);
      const remainder = data.length % 3;
      pictureList.value = [
        data.slice(0, num),
        data.slice(num, 2 * num),
        data.slice(2 * num, 3 * num),
      ];
      Array(remainder).fill("").forEach((item, index) => {
        if (!data[data.length - remainder + index]) return false;
        if (!pictureList.value[index]?.length) pictureList.value[index] = [];
        pictureList.value[index].push(data[data.length - remainder + index]);
      });
      console.log(pictureList.value);
      pictureList.value?.[0]?.[0] && handlerPicItem(pictureList.value[0][0]);
    })
    .catch((error) => {
      window.$message.error(error || "获取图片失败");
    })
    .finally(() => {
      loading.value = false;
    });
};

// 编辑图片表单
const currentPictrue: Ref<any> = ref({}); // 当前选中的图片
const formRef = ref(null);
const editForm = reactive({
  isShow: "1",
  title: "",
  picTags: "",
  captureTime: null,
  description: "",
  pixelWidth: "",
  pixelHeight: "",
  aperture: "",
  focalLength: "",
  shutter: "",
  iso: "",
});
const rules = reactive({});

onMounted(() => {
  refreshData();
});

// 下一页
const nextPage = () => {
  if (pageSize.value * pageNumber.value >= total.value) return;
  pageNumber.value++;
  refreshData();
};

const handlerUpdatePage = (page: number) => {
  pageNumber.value = page;
  refreshData();
};

// 提交审核
const handlerSubmitReview = (pictrue: any) => {
  loading.value = true;
  updatePicture({
    is_approved: "1",
    pid: pictrue?.pid
  }).then((res: any) => {
    if (res.status === "success") {
      window.$message.success(res.msg || "审核成功");
      // refreshData();
    } else {
      window.$message.success(res.msg || "修改失败");
    }
  }).catch((error) => {
    window.$message.success(error || "修改失败");
  }).finally(() => {
    loading.value = false;
  });
};

// 修改当前图片
const handlerPicItem = (pictrue: any) => {
  const pic: any = exchangeKey(pictrue);
  Object.keys(editForm).forEach((key: string) => {
    if (key === "title") {
      editForm[key] = pic.title || pic.name;
    } else {
      editForm[key] = pic[key];
    }
  });
  currentPictrue.value = pic;
};

// 修改单张照片信息
const editPicture = () => {
  const params = Object.assign({}, editForm, {
    pid: currentPictrue.value?.pid
  })
  loading.value = true;
  updatePicture(params).then((res: any) => {
    if (res.status === "success") {
      window.$message.success(res.msg || "修改成功");
      // refreshData();
    } else {
      window.$message.success(res.msg || "修改失败");
    }
  }).catch((error) => {
    window.$message.success(error || "修改失败");
  }).finally(() => {
    loading.value = false;
  });
};

defineExpose({
  refresh: refreshData,
});
</script>
<style lang="less" scoped>
@import "../styles/picture-list.less";
</style>
